package com.zrb.mobile;

import org.apache.http.Header;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zrb.mobile.adapter.model.RegisterDto;
import com.zrb.mobile.adapter.model.UserDtos;
import com.zrb.mobile.adapter.model.UserRegisterInfoDto;
import com.zrb.mobile.common.OnlineServer;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.Constants;
import com.zrb.mobile.utility.DialogBuilder;
import com.zrb.mobile.utility.ZrbRestClient;

import com.zrb.applib.utils.AppSetting;
import com.zrb.applib.utils.LocalUserInfo;

import android.location.Location;
import android.os.Bundle;
import android.app.Dialog;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class User_registerBase1 extends RegisterBaseActivity implements
		OnClickListener {

	LinearLayout layout_top, layout_choose, layout_successhite;
	TextView lienceRead, liencedown, txtTitle;
	EditText edituserName;
	TextView mlocationTxt, mindustryTxt;
	Button finishBtn;
	boolean isfinish = false;
	private String areaCode;
	ImageView successImg;
	Button nextBtn;
	String registerPhone;
	String registerPwd;
	Dialog PopDialog;
	private LocationManagerProxy mLocationManagerProxy;

	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.u_center_registerbase_step1);
		if (bundle != null)
			restoreSelf(bundle);
		else {
			registerPhone = this.getIntent().getStringExtra("phonenum");
			registerPwd = this.getIntent().getStringExtra("pwd");
			isfinish = this.getIntent().getBooleanExtra("isfinish", false);
		}
		initView();
		if (!isfinish)
			init();

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString("registerPhone", registerPhone);
		outState.putString("pwd", registerPwd);
	}

	private void restoreSelf(Bundle savedInstanceState) {
		registerPhone = savedInstanceState.getString("registerPhone");
		registerPwd = savedInstanceState.getString("pwd");
	}

	protected void initView() {
		// this.findViewById(R.id.title_left_root).setOnClickListener(this);
		super.initView();
		txtTitle = (TextView) this.findViewById(R.id.txt_title);
		txtTitle.setText("基本信息");

		mlocationTxt = (TextView) this.findViewById(R.id.tv_location_value);
		mindustryTxt = (TextView) this.findViewById(R.id.tv_industry_value);
		edituserName = (EditText) this.findViewById(R.id.edit_temp_name);

		this.findViewById(R.id.title_left_root).setOnClickListener(this);
		this.findViewById(R.id.re_industry).setOnClickListener(this);
		this.findViewById(R.id.re_location).setOnClickListener(this);

		nextBtn = (Button) this.findViewById(R.id.send_btn);
		nextBtn.setOnClickListener(this);
		nextBtn.setEnabled(true);

		if (isfinish) {
			this.findViewById(R.id.re_tmpname_layout).setVisibility(View.GONE);
			this.findViewById(R.id.re_location).setVisibility(View.GONE);
			this.findViewById(R.id.re_industry).setVisibility(View.GONE);
			nextBtn.setText("立即体验");
			this.findViewById(R.id.btn_step_process).setEnabled(true);
			this.findViewById(R.id.line_step_start).setSelected(true);

			this.findViewById(R.id.btn_step_finish).setEnabled(true);
			this.findViewById(R.id.line_step_finish).setSelected(true);

		}
	}

	/**
	 * 初始化定位
	 */
	private void init() {
		// 初始化定位，只采用网络定位
		mLocationManagerProxy = LocationManagerProxy.getInstance(this);
		mLocationManagerProxy.setGpsEnable(false);
		// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
		// 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用removeUpdates()方法来取消定位请求
		// 在定位结束后，在合适的生命周期调用destroy()方法
		// 其中如果间隔时间为-1，则定位只定一次,
		// 在单次定位情况下，定位无论成功与否，都无需调用removeUpdates()方法移除请求，定位sdk内部会移除
		mLocationManagerProxy.requestLocationData(
				LocationProviderProxy.AMapNetwork, 60 * 1000, 15, tmpLocation);
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (mLocationManagerProxy != null) {
			// 移除定位请求
			mLocationManagerProxy.removeUpdates(tmpLocation);
			// 销毁定位
			mLocationManagerProxy.destroy();
		}
	}

	AMapLocationListener tmpLocation = new AMapLocationListener() {

		@Override
		public void onLocationChanged(Location location) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onLocationChanged(AMapLocation amapLocation) {
			// TODO Auto-generated method stub
			if (amapLocation != null
					&& amapLocation.getAMapException().getErrorCode() == 0) {
				// 定位成功回调信息，设置相关消息
				/*
				 * mLocationLatlngTextView.setText(amapLocation.getLatitude() +
				 * "  " + amapLocation.getLongitude());
				 * mLocationAccurancyTextView
				 * .setText(String.valueOf(amapLocation .getAccuracy()));
				 * mLocationMethodTextView.setText(amapLocation.getProvider());
				 * 
				 * SimpleDateFormat df = new
				 * SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new
				 * Date(amapLocation.getTime());
				 * 
				 * mLocationTimeTextView.setText(df.format(date));
				 * mLocationDesTextView.setText(amapLocation.getAddress());
				 */
				/*
				 * if (amapLocation.getProvince() == null) {
				 * mLocationProvinceTextView.setText("null"); } else {
				 * mLocationProvinceTextView
				 * .setText(amapLocation.getProvince()); }
				 * mLocationCityTextView.setText(amapLocation.getCity());
				 * mLocationCountyTextView.setText(amapLocation.getDistrict());
				 * mLocationCityCodeTextView
				 * .setText(amapLocation.getCityCode());
				 * mLocationAreaCodeTextView.setText(amapLocation.getAdCode());
				 */

				mlocationTxt.setText(amapLocation.getProvince() + " "
						+ amapLocation.getCity());
				//areaCode = amapLocation.getAdCode();
				areaCode = amapLocation.getAdCode().substring(0, 4) + "00";
				// mlocationTxt.setTag(amapLocation.getAdCode());
			}
		}
	};

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.title_left_root:
			GetBack();
			break;
		case R.id.re_location:
			Intent it = new Intent(User_registerBase1.this,
					User_locationActivity.class);
			it.putExtra("isucenter", true);
			this.startActivityForResult(it, 100);
			break;
		/*
		 * case R.id.finish_btn: Intent it4 = new
		 * Intent(User_registerBase1.this, User_phone_login.class);
		 * user_Login(); this.finish(); break;
		 */
		case R.id.send_btn:
			if (isfinish)
				user_Login();
			else
				saveStep1();
			break;
		case R.id.re_industry:
			Intent it6 = new Intent(User_registerBase1.this,
					User_registerIndustry.class);
			it6.putExtra("isProject", true);
			this.startActivityForResult(it6, 110);
			break;
		}
	}

	private void user_Login() {

		showloading("登陆中...");
		RequestParams param = new RequestParams();
		param.put("name", registerPhone);
		param.put("password", registerPwd);

		// String loginurlparms = "?name=" + name + "&password="+ password;
		ZrbRestClient.post("dologin", param, new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				// TODO Auto-generated method stub
				progTip.Dismiss();
				initNotify("服务端网络连接出错");
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				// TODO Auto-generated method stub
				progTip.Dismiss();
				String results = new String(arg2);
				try {
					Gson gson = new Gson();
					UserDtos tmpDto = gson.fromJson(results, UserDtos.class);
					if (tmpDto.res == 1) {
						AppSetting.curUser = tmpDto.data;
						AppSetting.curUser.pwd = registerPwd;
						LocalUserInfo.getInstance(User_registerBase1.this)
								.saveUserInfo(tmpDto.data);
						 boolean hasGuide=	LocalUserInfo.getInstance(User_registerBase1.this).hasGuide();
						 if(hasGuide){
							 User_registerBase1.this.finish();
								CommonUtil.InfoLog("Regin_Success_FINISH", "注册成功");
								Intent intent=new Intent(Constants.Regin_Success_FINISH);
								sendBroadcast(intent);
						 }else{
							 Intent intent=new Intent(User_registerBase1.this, MainTabActivity.class);
							 startActivity(intent);
							 User_registerBase1.this.finish();
						 }
						
						

					} else {
						initNotify(tmpDto.msg);
					}
				} catch (Exception e) {
					initNotify(User_registerBase1.this
							.getString(R.string.error_serverdata_loadfail));
				}

			}
		});
	}

	private void saveStep1() {
		showloading("提交中...");
		RequestParams param = new RequestParams();

		param.put("phone", registerPhone);
		param.put("realname", edituserName.getText().toString());
		CommonUtil.InfoLog("locationId", areaCode + "");
		param.put("locationId", areaCode);
		if (mindustryTxt.getTag() != null) {
			param.put("industry", mindustryTxt.getText());
			param.put("industryId", mindustryTxt.getTag().toString());
		}
		CommonUtil.InfoLog("saveUserInfoApiparam", param.toString());
		ZrbRestClient.post("register/saveUserInfoApi", param,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						// TODO Auto-generated method stub
						hideloading();
						initNotify("网络出错");
					}

					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
						// TODO Auto-generated method stub
						progTip.Dismiss();
						String results = new String(arg2);
						CommonUtil.InfoLog("saveUserInfoApi", results);
						try {
							Gson gson = new Gson();
							RegisterDto tmpDto = gson.fromJson(results,
									RegisterDto.class);
							if (tmpDto.res == 1) {
								Intent it5 = new Intent(
										User_registerBase1.this,
										User_registerBase2.class);
								it5.putExtra("phonenum", registerPhone);
								it5.putExtra("pwd", registerPwd);
								startActivity(it5);
							} else {
								initNotify(tmpDto.msg);
							}
						} catch (Exception e) {
							initNotify("网络出错");

						}
					}
				});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == android.app.Activity.RESULT_OK) {
			switch (requestCode) {
			case 100:
				String curArea = data.getStringExtra("area");
				String curCode = data.getStringExtra("code");
				CommonUtil.InfoLog("curArea", curArea + "");
				CommonUtil.InfoLog("curCode", curCode + "");
				mlocationTxt.setText(curArea);
 			 
				areaCode=curCode.contains(",") ?curCode.split(",")[1]:curCode;
				
				// if(curArea.contains(" ")) {
				// mlocationTxt.setText(curArea);//.split(" ")[1]
				// areaCode=curCode.substring(start);
				// //mlocationTxt.setTag(curCode);
				// }
				// else{
				// mlocationTxt.setText(curArea);
				// areaCode= areaCode.contains(",") ?areaCode.split(",")[1]
				// :areaCode;
				// //mlocationTxt.setTag(curCode);
				// }
				break;
			case 110:
				String industryname = data.getStringExtra("name");
				int industryCode = data.getIntExtra("code", -1);
				mindustryTxt.setText(industryname);
				mindustryTxt.setTag(industryCode);
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			// ��Ҫ������¼�
			GetBack();

			return false;
		}
		return super.dispatchKeyEvent(event);
	}

	private void GetBack() {
		DialogBuilder builder2 = new DialogBuilder(User_registerBase1.this);
		// builder2.setTheme(Resource.Style.customDialog);
		builder2.setTitle("中断填写?");
		builder2.setShowAlert(true);
		View view = View.inflate(User_registerBase1.this,
				R.layout.exitsystem_dialog_view, null);
		TextView textView = (TextView) view.findViewById(R.id.tips);
		textView.setText("你离招融宝只有一步之遥了，真的要放弃吗?");
		builder2.setContentView(view);
		builder2.setPositiveTitle("先不填了");
		builder2.setNegativeButtonText("继续填写");
		builder2.setCloseOnclick(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				PopDialog.dismiss();
				if (arg0.getId() == R.id.btn_confirm) {
					User_registerBase1.this.finish();
				}
			}
		});
		PopDialog = builder2.create();
		PopDialog.show();
	}

}
